<?php
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;

/**
 * @return Application
 * 获取微信app
 */
function weixin_get_app() {
    $p = [
        'app_id'    => Wx_Config::WEIXIN_APPID,
        'secret'    => Wx_Config::WEIXIN_APPSECRET,
        'token'     => Wx_Config::WEIXIN_TOKEN,
        'aes_key'   => Wx_Config::WEIXIN_EncodingAESKey,
    ];

    return $app = Factory::officialAccount($p);
}
function weixin_payment_app() {
    $p = [
        'app_id'    => Wx_Config::WEIXIN_APPID,
        'secret'    => Wx_Config::WEIXIN_APPSECRET,
        'token'     => Wx_Config::WEIXIN_TOKEN,
        'aes_key'   => Wx_Config::WEIXIN_EncodingAESKey,
        'mch_id'        => Wx_Config::MCH_ID,
        'key'                => Wx_Config::MCH_KEY,
        'cert_path'          => Wx_Config::CERT_PATH, // XXX: 绝对路径！！！！
        'key_path'           => Wx_Config::KEY_PATH,      // XXX: 绝对路径！！！！
//        'notify_url'         => 'https://www.huilinle.com/payment/notify',       // 你也可以在下单时单独设置来想覆盖它

    ];

    return $app = Factory::payment($p);
}
function weixin_hb_app() {
    $p = [
        'app_id'    => Wx_Config::WEIXIN_APPID,
        'secret'    => Wx_Config::WEIXIN_APPSECRET,
        'token'     => Wx_Config::WEIXIN_TOKEN,
        'aes_key'   => Wx_Config::WEIXIN_EncodingAESKey,
        'mch_id'        => Wx_Config::HB_MCH_ID,
        'key'                => Wx_Config::MCH_KEY,
        'cert_path'          => Wx_Config::CERT_PATH, // XXX: 绝对路径！！！！
        'key_path'           => Wx_Config::KEY_PATH,      // XXX: 绝对路径！！！！
//        'notify_url'         => 'https://www.huilinle.com/payment/notify',       // 你也可以在下单时单独设置来想覆盖它

    ];

    return $app = Factory::payment($p);
}
/**
 * @param $message
 * @return mixed
 * 发送微信消息
 */
function weixin_message_send($open_id, $msg) {
    $ret['status'] = FALSE;
    if($msg) {
        try {
            $app = weixin_get_app();
            $message = new Text($msg);
            $result = $app->customer_service->message($message)->to($open_id)->send();
            $ret['status'] = TRUE;
        }catch (Exception $e) {
            $ret['info'] = $e->getMessage();
        }
    }
    return $ret;
}

/**
 * @param $message
 * 模板消息
 */
function weixin_template_message_send($message) {
    $ret['status'] = FALSE;
    if($message) {
        try {
            $app = weixin_get_app();
            $notice = $app->notice;
            $notice->send([
                'touser'        => $message['openid'],
                'template_id'   => $message['templateid'],
                'url'           => $message['url'],
                'topcolor'      => $message['color'],
                'data'          => $message['data']
            ]);
            $ret['status'] = TRUE;
        }catch (Exception $e) {
            $ret['info'] = $e->getMessage();
        }
    }
    return $ret;
}

/**
 * @param $user_service
 * @param $openid
 * @return mixed
 * 获取微信原始用户数据
 */
function weixin_get_user_info($openid) {
    $ret = FALSE;
    try {
        $app = weixin_get_app();
        $user_service = $app->user;
        $ret['user_info'] = $user_service->get($openid);
        if($ret['user_info']['openid']) {
            $ret['status'] = TRUE;
        } else {
            $ret['info'] = $ret['errmsg'] = '信息可能有误，请核查';
        }
    } catch (Exception $e) {
        $ret['info'] = $e->getMessage();
    }
    return $ret;
}



/**
 * @param $scene_id
 * @return string
 * 获取微信临时二维码
 */
function weixin_get_qrcode($scene_id = 1, $expire_sec = 2592000) {
    $ret = ['status' => FALSE];
    $app = weixin_get_app();
    $qrcode = $app->qrcode;

    //创建时长30天的临时二维码
    $qrcode_result = $qrcode->temporary($scene_id, $expire_sec);

    if($qrcode_result){
        $qrcode_url = $qrcode->url($qrcode_result['ticket']);
        $up_data = [
            'qrcode_url' => $qrcode_url,
            'expired_time' => time()+2592000,
        ];
        db_update('qrcode', $up_data, ['id' => $scene_id]);
        $qrcode_data = db_get_obj('qrcode', ['id' => $scene_id]);
        $ret['url'] = $qrcode_data['qrcode_url'];
        $ret['status'] = TRUE;
    }
    return $ret;
}


function weixin_order($body, $out_trade_no, $total_fee, $openid, $notify_url){
    $attributes = [
        'body'             => $body,
        'detail'           => $body,
        'out_trade_no'     => $out_trade_no,
        'total_fee'        => $total_fee,
        'openid'        => $openid,
        'trade_type'        => 'JSAPI',
        'notify_url'       => resource('notify_url', $notify_url), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
    ];
    $app = weixin_payment_app();
    $result = $app->order->unify($attributes);
    $jssdk = $app->jssdk;
//    $jssdk = json_decode($jssdk, true);
    $json = $jssdk->bridgeConfig($result['prepay_id']);
//    dump($attributes);
//    dump($result);
    return $json;
}

/**
 * 微信支付订单号前缀说明：
 * RENEW 商家续费 shop_renew表 成功 state=1 失败 state=-1
 * A 赞赏 article_zanshang表
 * P meinv_zanshang表 凭美赞赏
 * G 商品购买
 */

function article_notify(){
    $app = weixin_payment_app();

    $response = $app->handlePaidNotify(function($message, $fail){
        // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
        $order = db_get_obj('article_buy', ['id' => $message['out_trade_no']]);
        if (!$order || $order['state'] == 0) { // 如果订单不存在 或者 订单已经支付过了
            return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
        }
        ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////
        $CI = &get_instance();
        if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
            $article = article_get($order['article_id'], 1);
            $CI->db->trans_start();
            // 用户是否支付成功
            if ($message['result_code'] === 'SUCCESS') {
                //支付成功相关数据处理
                db_update('article_buy', ['state' => 1, 'payment_time' => time(), 'transaction_id' => $message['transaction_id']], ['id' => $order['id']]);
                article_update($article, ['pay' => 1, 'pay_type' => 1]);

                // 用户支付失败
            } elseif ($message['result_code'] === 'FAIL') {
                $order->status = 'paid_fail';
            }
            $CI->db->trans_complete();
        } else {
            return $fail('通信失败，请稍后再通知我');
        }
        return true; // 返回处理完成
    });

    $response->send(); // return $response;
}

function activity_notify(){
    $app = weixin_payment_app();
    $response = $app->handlePaidNotify(function($message, $fail){
        // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
        $order_id = str_replace('HD_GOODS', '', $message['out_trade_no']);
        payment_article_log($message['out_trade_no'], $order_id);
        $order = db_get_obj('orders', ['id' => $order_id]);

        if (!$order || $order['state'] != 0) { // 如果订单不存在 或者 订单已经支付过了
            return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
        }
        ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////

        if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
            // 用户是否支付成功
            if ($message['result_code'] === 'SUCCESS') {
                $user = user_get($order['uid']);
                $b_user = user_get($order['a_uid']);
                if($order['state'] == 0){
                    $CI = &get_instance();
                    $CI->db->trans_start();
                    //支付成功相关数据处理
                    $code = mt_rand(100000, 999999);
                    db_update('orders', ['state' => 1, 'payment_time' => time(), 'transaction_id' => $message['transaction_id'], 'code' => $code], ['id' => $order['id']]);
                    //给用户发送订单支付通知
                    goods_buy_tx($user, $order, $code);
                    //给商家新订单提现
                    shop_order_tx($b_user, $order, $code);
                    $CI->db->trans_complete();
                }
                // 用户支付失败
            } elseif ($message['result_code'] === 'FAIL') {
                //
                db_update('orders', ['state' => -1, 'payment_time' => time(), 'transaction_id' => $message['transaction_id']], ['id' => $order['id']]);
            }
        } else {
            return $fail('通信失败，请稍后再通知我');
        }
        return true; // 返回处理完成

    });
    $response->send();
}

function hui_notify(){
    $app = weixin_payment_app();
    $response = $app->handlePaidNotify(function($message, $fail){
        // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
        $order_id = str_replace('HUI', '', $message['out_trade_no']);
        payment_article_log($message['out_trade_no'], $order_id);
        $order = db_get_obj('fx_hui', ['id' => $order_id]);

        if (!$order || $order['state'] != 2) { // 如果订单不存在 或者 订单已经支付过了
            return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
        }
        ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////

        if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
            // 用户是否支付成功
            if ($message['result_code'] === 'SUCCESS') {
                $user = user_get($order['uid']);
                $b_user = user_get($order['a_uid']);
                if($order['state'] == 0){
                    $CI = &get_instance();
//                    $CI->db->trans_start();
                    //支付成功相关数据处理
                    db_update('fx_hui', ['state' => 3, 'payment_time' => time(), 'transaction_id' => $message['transaction_id']], ['id' => $order['id']]);
//                    $CI->db->trans_complete();
                }
                // 用户支付失败
            } elseif ($message['result_code'] === 'FAIL') {
            }
        } else {
            return $fail('通信失败，请稍后再通知我');
        }
        return true; // 返回处理完成

    });
    $response->send();
}

/**
 * @param $red
 * 红包前缀说明：
 * lhb 赞助商红包
 * P 美照奖励
 * FL平台福利红包
 */

function pic_luckyMoney( $pic_red ){
    $app = weixin_get_app();
    $pic_red = is_array($pic_red) ? $pic_red : db_get_obj('pic_red', array('id' => $pic_red));
    if($pic_red){
        if( $pic_red['state'] == 0 || $pic_red['state'] == -1 ){
            $user = user_get($pic_red['uid']);
            $luckyMoney = $app->lucky_money;
            $luckyMoneyData = [
                'mch_billno'       => 'P'.$pic_red['id'],
                'send_name'        => '美照奖励',
                're_openid'        => $user['openid'],
                'total_num'        => 1,  //固定为1，可不传
                'total_amount'     => $pic_red['amount'],  //单位为分，不小于300
                'wishing'          => '你最美',
                'client_ip'        => '',  //可不传，不传则由 SDK 取当前客户端 IP
                'act_name'         => '测试活动',
                'remark'           => '测试备注',
                // ...
            ];

            $result = $luckyMoney->sendNormal($luckyMoneyData);
            if($result->result_code == 'SUCCESS'){
                db_update('pic_red', array('state' => 1), array('id' => $pic_red['id']));
            }
            $in_data = array(
                'pid' => $pic_red['id'],
                'uid' => $user['id'],
                'return_code' => $result->return_code,
                'return_msg' => $result->return_msg,
                'result_code' => $result->result_code,
                'err_code' => $result->err_code,
                'err_code_des' => $result->err_code_des,
                'mch_billno' => $result->mch_billno,
                'mch_id' => $result->mch_id,
                'wxappid' => $result->wxappid,
                're_openid' => $result->re_openid,
                'total_amount' => $result->total_amount,
                'send_listid' => $result->send_listid,
                'ctime' => time(),
            );
            db_insert('pm_red_log', $in_data);
        }
    }
}
//计算用户的红包是否大于1块钱
function js_user_hb($user){
    $amount = db_sum_record('lhb', ['uid' => $user['id'], 'pay_state' => 0, 'order_id' => 0], 'amount');
    if ($amount >= 100) {
        $id = db_insert('lhb_order', ['uid' => $user['id'], 'amount' => $amount, 'ctime' => time()]);
        db_update('lhb', ['order_id' => $id], ['uid' => $user['id'], 'pay_state' => 0, 'order_id' => 0]);
        zz_red($id);
    } else {
        if ($amount == 0) {
            weixin_message_send(['message' => '你没有可发放的红包', 'openid' => $user['openid']]);
        } else {
            weixin_message_send(['message' => '你已经领到'.finance_amount_yuan($amount).'元红包，满1元系统自动发放', 'openid' => $user['openid']]);
        }
    }
}

//赞助商红包
function zz_red( $red ){
    $app = weixin_get_app();
    $red = is_array($red) ? $red : db_get_obj('lhb_order', array('id' => $red));
//    $red = is_array($red) ? $red : db_get_obj('lhb', array('id' => $red));
    if($red){
        if( $red['pay_state'] == 0 || $red['pay_state'] == -1 ){
            $user = user_get($red['uid']);
            $luckyMoney = $app->lucky_money;
            $luckyMoneyData = [
                'mch_billno'       => 'lhb'.$red['id'],
                'send_name'        => '赞助商助学红包',
                're_openid'        => $user['openid'],
                'total_num'        => 1,  //固定为1，可不传
                'total_amount'     => $red['amount'],  //单位为分，不小于300
                'wishing'          => '祝您学习快乐',
                'client_ip'        => '',  //可不传，不传则由 SDK 取当前客户端 IP
                'act_name'         => '赞助商助学红包',
                'remark'           => '赞助商助学红包',
                // ...
            ];

            $result = $luckyMoney->sendNormal($luckyMoneyData);
//dump($result);
            if($result->result_code == 'SUCCESS'){
                db_update('lhb_order', array('pay_state' => 1), array('id' => $red['id']));
                $in_data = array(
                    'pid' => $red['id'],
                    'uid' => $user['id'],
                    'return_code' => $result->return_code,
                    'return_msg' => $result->return_msg,
                    'result_code' => $result->result_code,
                    'err_code' => $result->err_code,
                    'err_code_des' => $result->err_code_des,
                    'mch_billno' => $result->mch_billno,
                    'mch_id' => $result->mch_id,
                    'wxappid' => $result->wxappid,
                    're_openid' => $result->re_openid,
                    'total_amount' => $result->total_amount,
                    'send_listid' => $result->send_listid,
                    'ctime' => time(),
                );
                db_insert('hb_log', $in_data);
            }
        }
    }
}
function lucky_money_query($pid){
    $mchBillNo = 'lhb'.$pid;
    $app = weixin_get_app();
    $luckyMoney = $app->lucky_money;
    return $luckyMoney->query($mchBillNo);
}
//商品支付
function goods_notify(){
    $app = weixin_get_app();
    $response = $app->payment->handleNotify(function($notify, $successful){
        // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
        $order_arr = json_decode($notify,true);
        $order_id = str_replace('G', '', $order_arr['out_trade_no']);
        $order = db_get_obj('orders', array('id' => $order_id));
        payment_goods_log($order_id,$notify);
        // 如果订单存在
        if($order){
            // 用户是否支付成功
            $CI = &get_instance();
            if ($successful) {
                $CI->db->trans_start();
                if($order['state'] == 0){
                    //支付成功相关数据处理
                    db_update('orders', array('state' => 1, 'payment_time' => time(), 'transaction_id' => $order_arr['transaction_id']), array('id' => $order['id']));
                    $order = db_get_obj('orders', array('id' => $order['id']));
                    goods_buy_tx(user_get($order['uid']), $order);
                }
                $CI->db->trans_complete();
                // 已经支付成功了就不再更新了
                return true;
            } else {
                // 用户支付失败
                $CI->db->trans_start();
                db_update('orders', array('state' => -1, 'payment_time' => time(), 'transaction_id' => $order_arr['transaction_id']), array('id' => $order['id']));
                $CI->db->trans_complete();
            }
        }else{
            // 如果订单不存在
            return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
        }
        return true; // 返回处理完成
    });

    return $response;
}


//FL福利红包前缀 tid:1零钱 2积分兑换红包
function luckyMoney( $red ){
    $mch_billno_str = 'FL';
    $app = weixin_get_app();
    $red = is_array($red) ? $red : db_get_obj('lhb_order', array('id' => $red));
    if($red){
        if ($red['state'] == 0 || $red['state'] == -1) {
            $send_name = '抽奖';
            if ($red['tid'] == 1) {
                $send_name = '抽奖';
            }
            $user = user_get($red['uid']);
            $luckyMoney = $app->lucky_money;
            $luckyMoneyData = [
                'mch_billno'       => $mch_billno_str.$red['id'],
                'send_name'        => $send_name,
                're_openid'        => $user['openid'],
                'total_num'        => 1,  //固定为1，可不传
                'total_amount'     => $red['amount'],  //单位为分，不小于300
                'wishing'          => '祝您开心',
                'client_ip'        => '',  //可不传，不传则由 SDK 取当前客户端 IP
                'act_name'         => '测试活动',
                'remark'           => '测试备注',
                // ...
            ];

            $result = $luckyMoney->sendNormal($luckyMoneyData);
            if($result->result_code == 'SUCCESS'){
                db_update('lhb_order', array('state' => 1), array('id' => $red['id']));
                $in_data = array(
                    'pid' => $red['id'],
                    'uid' => $user['id'],
                    'return_code' => $result->return_code,
                    'return_msg' => $result->return_msg,
                    'result_code' => $result->result_code,
                    'err_code' => $result->err_code,
                    'err_code_des' => $result->err_code_des,
                    'mch_billno' => $result->mch_billno,
                    'mch_id' => $result->mch_id,
                    'wxappid' => $result->wxappid,
                    're_openid' => $result->re_openid,
                    'total_amount' => $result->total_amount,
                    'send_listid' => $result->send_listid,
                    'ctime' => time(),
                );
                db_insert('hb_log', $in_data);
            }
        }
    }
}

